package Netty_basic;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;

import java.net.SocketAddress;
import java.util.Scanner;

public class Sim_client {
    public static void main(String[] args) throws InterruptedException {
            test1();
    }

    public static void test1() throws InterruptedException {
        new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect("localhost",8080)
                .sync()//等待connect方法建立好连接，因为connect是异步的
                .channel()
                .writeAndFlush("hello!Server!");//写入消息并清空缓冲区
    }

    //CloseFuture，优雅的关闭
    public static void test2() throws InterruptedException {
        NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup();
        ChannelFuture cf = new Bootstrap()
                .group(nioEventLoopGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                }).connect("localhost", 8080);


        Channel channel = cf.sync().channel();
        System.out.println(channel);
        new Thread(()->{
            Scanner scanner=new Scanner(System.in);
            while (true){
                String s=scanner.nextLine();
                if ("q".equals(s)){
                    channel.close();
                    break;
                }else {
                    channel.writeAndFlush(s);
                }
            }
        }).start();

        //获取closefuture对象
        ChannelFuture closeFuture = channel.closeFuture();
        //这里有两种选择
        //一是用sync，而是用listener
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println("正在处理关闭后的操作！");
                nioEventLoopGroup.shutdownGracefully();
            }
        });


    }


}
